package com.falcon.mvc.aop;

import com.swan.log.context.LogContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/** 将 Rest 接口响应值，统一包装成 BaseResponse 格式
 * @author zongf
 * @date 2024-02-08
 **/
@Slf4j
@Component
@WebFilter
@Order(1)
public class RequestLogFilter implements Filter {

    private static final String RESPONSE_LOG_ID = "LogId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LogContext.setLogId();

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        Long start = System.currentTimeMillis();

        log.info("请求开始, 请求类型:{}, 请求地址:{}", servletRequest.getMethod(), servletRequest.getRequestURI());

        try {
            chain.doFilter(servletRequest, servletResponse);
        } finally {
            // 响应头添加 LogId
            servletResponse.addHeader(RESPONSE_LOG_ID, LogContext.getLogId());

            // 清除请求id
            LogContext.cleanLodId();

            log.info("请求结束, 请求类型:{}, 请求地址:{}, 接口耗时:{} ms", servletRequest.getMethod(), servletRequest.getRequestURI(), System.currentTimeMillis() - start);
        }
    }



}
